<template>
  <div class="user">
    <div class="head">
      <!-- 查询 -->
      <el-form class="myfind">
        <!-- 下拉菜单 -->
        <el-form-item class="el1">
          <el-select v-model="sousuo" style="width : 8rem" placeholder="请选择筛选条件"> 
            <el-option label="用户id" value="id"/>
            <el-option label="用户账号" value="username"/>
            <el-option label="用户昵称" value="role"/>
          </el-select>
        </el-form-item>
        <!-- 输入框 -->
        <el-form-item class="el2">
          <el-input label="请输入" :placeholder="`请输入您要搜索的${sousuo}`" v-model.lazy.trim="gjz"/>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="onFind" class="b1" >搜索</el-button>
          <el-button type="warning" class="b2" @click="Reset">重置</el-button>
        </el-form-item>

      </el-form>

      <!-- 添加和删除功能按钮 -->
      <el-form class="myadd">
        
        <el-form-item>
          <el-button type="primary" @click="address">新增</el-button>
          <el-button type="danger" @click="dels">批量删除</el-button>
        </el-form-item>

      </el-form>
      
      <!-- 数据表单 -->
      <el-form class="mytable">
      <el-table :data="tableData"  style="width: 100%" ref="tableRef">
          <el-table-column type="selection" width="55" />
          <el-table-column label="id" width="120" prop="id" />
          <el-table-column label="账号" width="120" prop="username"/>
          <el-table-column label="身份" width="120" prop="role"/>
          <el-table-column label="昵称" width="120" prop="nickname"/>
          <el-table-column label="电话" width="200" prop="phone"/>
          <el-table-column label="邮箱" width="200" prop="email"/>
          <el-table-column label="地址" width="300" prop="address"/>
          <el-table-column label="操作" width="200" >

          <template #default="scope">  
            <el-button type="success" @click="change(scope.row)">编辑</el-button>
            <el-button type="danger" @click="delUser(scope.row)">删除</el-button>
          </template>  
          </el-table-column>
          
      </el-table>
      </el-form>
      
      <!-- 分页器 -->
    <div class="demo-pagination-block">
      <el-pagination
        v-model:current-page="currentPage2"
        v-model:page-size="pageSize2"
        :page-sizes="[5, 6, 7, 8]"
        :size="size"
        :disabled="disabled"
        :background="background"
        layout="sizes, prev, pager, next"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        />
    </div>
    </div>

    <!-- 新增用户对话框 -->
    <el-dialog v-model="dialogVisible" title="新增用户">
      
        <el-form :model="newUser" :rules="userRules" ref="userFormRef">
          <el-form-item label="账号" prop="username">
            <el-input v-model="newUser.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="newUser.password" show-password></el-input>
          </el-form-item>
          <el-form-item label="昵称" prop="nickname">
            <el-input v-model="newUser.nickname"></el-input>
          </el-form-item>
          <el-form-item label="身份" prop="role">
            <el-select
              v-model="newUser.role"
              placeholder="请选择身份"
              clearable
            >
              <el-option label="管理员" value="admin" />
              <el-option label="新用户" value="user" />
            </el-select>
          </el-form-item>  
          <el-form-item label="电话" prop="phone">
            <el-input v-model="newUser.phone"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="newUser.email"></el-input>
          </el-form-item>
          <el-form-item label="地址" prop="address">
            <el-input v-model="newUser.address"></el-input>
          </el-form-item>
        </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveUser">确定</el-button>
      </template>
    </el-dialog>


   <!-- 编辑用户对话框 -->
    <el-dialog v-model="bianji" title="编辑用户">
        <el-form :model="editUser" :rules="userRules" ref="userFormRef">
          <el-form-item label="昵称" prop="nickname">
            <el-input v-model="editUser.nickname"></el-input>
          </el-form-item>
          <el-form-item label="身份" prop="role">
            <el-select
              v-model="editUser.role"
              placeholder="请选择身份"
              clearable
            >
              <el-option label="管理员" value="admin" />
              <el-option label="新用户" value="user" />
            </el-select>
          </el-form-item>  
          <el-form-item label="电话" prop="phone">
            <el-input v-model="editUser.phone"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editUser.email"></el-input>
          </el-form-item>
          <el-form-item label="地址" prop="address">
            <el-input v-model="editUser.address"></el-input>
          </el-form-item>
        </el-form>

      <template #footer>
        <el-button @click="bianji = false">取消</el-button>
        <el-button type="primary" @click="saveEditUser">确定</el-button>
      </template>
      
    </el-dialog>
  </div>
</template>

<script setup>
import { inject, ref, reactive } from "vue";
import { ElMessage, ElMessageBox } from 'element-plus';
import { md5 } from 'js-md5'; // 引入 md5 加密库

const gjz = ref('');
const sousuo = ref('');
const tableData = ref([]);
const originalTableData = ref([]); // 用于存储原始数据
const dialogVisible = ref(false); // 控制新增对话框显示隐藏
const bianji = ref(false); // 控制编辑对话框显示隐藏
const newUser = reactive({
  username: '',
  newPassword: '',
  role: '',
  nickname: '',
  phone: '',
  email: '',
  address: ''
});

const userFormRef = ref(null);
const tableRef = ref(null); // 表格的 ref

// 分页相关数据
const currentPage2 = ref(1);
const pageSize2 = ref(5);
const total = ref(0);

// 验证规则对象
const userRules = reactive({
  username: [
    { required: true, message: '必须填写账号！', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '必须填写密码！', trigger: 'blur' }
  ]
});

// 启动页面显示后端数据
const $axios = inject('$axios');
const loadData = () => {
  $axios.get(`http://localhost:9191/user/page?pageNum=${currentPage2.value}&pageSize=${pageSize2.value}`).then((res) => {
    tableData.value = res.data.records;
    originalTableData.value = res.data.records;
    total.value = res.data.total; // 设置总记录数
  }).catch((error) => {
    console.log(error);
  });
};

loadData();

// 搜索功能
const onFind = () => {
  if (!gjz.value) {
    // 如果关键字为空，显示原始数据
    tableData.value = originalTableData.value;
    return;
  }
  tableData.value = originalTableData.value.filter(item => {
    const value = item[sousuo.value];
    if (value) {
      return String(value).toLocaleLowerCase().includes(gjz.value.toLocaleLowerCase());
    }
    return false;
  });
};

// 添加重置功能
const Reset = () => {
  gjz.value = '';
  sousuo.value = '';
  tableData.value = originalTableData.value;
};


// 新增功能
const address = () => {
  dialogVisible.value = true;
};
const saveUser = () => {
  userFormRef.value.validate((valid) => {
    if (valid) {
      // 对密码进行 MD5 加密
      newUser.newPassword = md5(newUser.password);
      console.log(newUser.newPassword);

      // 发送请求保存新用户
      $axios.post('http://localhost:9191/user', newUser).then((res) => {
        if (res.code === '200') {
          ElMessage.success('用户添加成功！');
          dialogVisible.value = false;
          
          

          // 重新加载数据
          loadData();
        } else {
          ElMessage.error(res.msg);
        }
      }).catch((error) => {
        ElMessage.error('添加用户失败，请稍后再试！');
        console.log(error);
      });
    } else {
      ElMessage.error('请填写完整信息！');
    }
  });
};

// 批量删除功能
const dels = () => {
  const selection = tableRef.value.getSelectionRows();
  if (selection.length === 0) {
    ElMessage.warning('请选择要删除的用户！');
    return;
  }

  // 收集所有选中用户的ID
  const ids = selection.map(item => item.id);
  console.log(ids);
  // 确认删除提示
  ElMessageBox.confirm(
    `确定要删除选中的 ${ids.length} 个用户吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 发送批量删除请求
    $axios.post('http://localhost:9191/user/del/batch', ids)
      .then((res) => {
        if (res.code === '200') {
          ElMessage.success('用户删除成功！');
          // 重新加载数据
          loadData();
        } else {
          ElMessage.error(res.msg || '删除失败，请重试');
        }
      })
      .catch((error) => {
        console.error('批量删除失败:', error);
        ElMessage.error('删除用户失败，请稍后再试！');
      });
  }).catch(() => {
    ElMessage.info('已取消删除操作');
  });
};

// 单个删除
const delUser = (row) => {
  const userId = row.id;
  // 确认删除提示
  ElMessageBox.confirm('确定要删除该用户吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 调用后端接口删除用户
    $axios.delete(`http://localhost:9191/user/${userId}`).then((res) => {
      if (res.code === '200') {
        ElMessage.success('用户删除成功！');
        // 重新加载数据
        loadData();
      } else {
        ElMessage.error(res.msg);
      }
    }).catch((error) => {
      ElMessage.error('删除用户失败，请稍后再试！');
      console.log(error);
    });
  }).catch(() => {
    // 用户取消删除操作
    ElMessage.info('已取消删除操作');
  });
};

// 分页器事件处理函数
const handleSizeChange = (newSize) => {
  pageSize2.value = newSize;
  loadData();
};

const handleCurrentChange = (newPage) => {
  currentPage2.value = newPage;
  loadData();
};

// 定义一个响应式对象来存放编辑数据
const editUser = reactive({
  id: '',
  username: '',
  password: '',
  role: '',
  nickname: '',
  phone: '',
  email: '',
  address: ''
});

// 编辑功能
const change = (row) => {
  // 将点击行的数据赋值给编辑对象
  Object.assign(editUser, row);
  bianji.value = true;
};

// 保存编辑后的用户信息
const saveEditUser = () => {
  userFormRef.value.validate((valid) => {
    if (valid) {
      // 发送请求更新用户信息
      $axios.post('http://localhost:9191/user', editUser).then((res) => {
        if (res.code === '200') {
          ElMessage.success('用户信息更新成功！');
          bianji.value = false;
          // 重新加载数据
          loadData();
        } else {
          ElMessage.error(res.msg);
        }
      }).catch((error) => {
        ElMessage.error('更新用户信息失败，请稍后再试！');
        console.log(error);
      });
    } else {
      ElMessage.error('请填写完整信息！');
    }
  });
};

</script>

<style scoped>
.user{
  width: 100%;
  padding: 2rem;
}

.user .head .myfind{
  width: 100%;
  display: flex;
}

.user .head .myfind .el1{
  padding-right: 1rem;
}

.user .head .myfind .el2{
  padding-right: 1rem;
}
.user .head .myfind  :deep(button>span){
    color: white;
    font-family: "黑体";
}
.user .head .myadd  :deep(button>span){
    color: white;
    font-family: "黑体";
}
.user .head .mytable  :deep(button>span){
    color: white;
    font-family: "黑体";
}
</style>